package cn.edu.sdjzu.xg23.kcsj01_backend.service.impl;

import cn.edu.sdjzu.xg23.kcsj01_backend.service.FileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
@Service
public class FileServiceImpl implements FileService {


    @Value("${file.upload.dir:E:/wenjian/temp/}")
    private String uploadDir;

    @Value("${file.url.prefix:wenjian/temp/}")
    private String urlPrefix;

    @Override
    public Map<String, Object> uploadFiles(MultipartFile[] files) {
        List<String> fileUrls = new ArrayList<>();
        List<String> originalFilenames = new ArrayList<>();

        // 确保上传目录存在
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        for (MultipartFile file : files) {
            if (file.isEmpty()) {
                continue;
            }

            try {
                // 生成唯一文件名
                String originalFilename = file.getOriginalFilename();
                String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
                String fileName = UUID.randomUUID() + fileSuffix;

                // 保存文件
                File dest = new File(uploadDir + fileName);
                file.transferTo(dest);

                // 构建URL
                String fileUrl = urlPrefix + fileName;

                // 记录结果
                fileUrls.add(fileUrl);
                originalFilenames.add(originalFilename);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        Map<String, Object> result = new HashMap<>();
        result.put("fileUrls", fileUrls);
        result.put("originalFilenames", originalFilenames);
        return result;
    }

    @Override
    public Map<String, Object> deleteFiles(List<String> fileUrls) {
        int successCount = 0;
        int failCount = 0;
        List<String> failedFiles = new ArrayList<>();

        for (String fileUrl : fileUrls) {
            // 构建完整文件路径
            String fullPath = uploadDir + fileUrl.replace(urlPrefix, "");
            File file = new File(fullPath);

            if (file.exists()) {
                if (file.delete()) {
                    successCount++;
                } else {
                    failCount++;
                    failedFiles.add(fileUrl);
                }
            } else {
                failCount++;
                failedFiles.add(fileUrl);
            }
        }

        Map<String, Object> result = new HashMap<>();
        result.put("successCount", successCount);
        result.put("failCount", failCount);
        result.put("failedFiles", failedFiles);
        return result;
    }

    @Override
    public boolean downloadFile(String filePath, HttpServletResponse response) throws IOException {
        // 构建完整文件路径 - 修复前缀重复问题
        String fullPath;

        // 检查filePath是否已包含urlPrefix
        if (filePath.startsWith(urlPrefix)) {
            // 移除重复的前缀部分
            fullPath = uploadDir + filePath.substring(urlPrefix.length());
        } else {
            // 正常拼接
            fullPath = uploadDir + filePath;
        }

        File file = new File(fullPath);

        // 检查文件是否存在
        if (!file.exists()) {
            return false;
        }

        // 处理文件名编码
        String fileName = URLEncoder.encode(file.getName(), StandardCharsets.UTF_8.toString())
                .replaceAll("\\+", "%20");

        // 设置响应头
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition",
                "attachment; filename*=UTF-8''" + fileName);
        response.setContentLength((int) file.length());

        // 流式传输文件
        try (FileInputStream fis = new FileInputStream(file);
             BufferedInputStream bis = new BufferedInputStream(fis)) {

            byte[] buffer = new byte[8192];
            OutputStream os = response.getOutputStream();
            int bytesRead;

            while ((bytesRead = bis.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }

            os.flush();
            return true;
        }
    }
}
